package com.lagouedu.consistentsession.controller;

import com.lagouedu.consistentsession.domain.User;
import com.lagouedu.consistentsession.service.LoginService;
import com.lagouedu.consistentsession.util.NetWorkUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
public class LoginController {

    @Value("${server.port}")
    private String port;

    @Autowired
    LoginService loginService;

    @RequestMapping("/login")
    public ResponseMessageVo loginController(User user, HttpServletRequest request){

        User user1 = loginService.checkLoginUser(user);
        if (user1==null) {
//            map.put("message","用户名或密码错误！");
            return new ResponseMessageVo("0","用户名或密码错误！");
        }
        //验证成功，生成sessionid 并将sessionid存入 session中
        HttpSession session = request.getSession();
        String sessionId = UUID.randomUUID().toString();
        session.setAttribute(String.valueOf(user1.getUserName()),sessionId);
        return new ResponseMessageVo("200", sessionId, user1);
    }

    @RequestMapping("/success")
    public ResponseMessageVo success(String userName, String sessionId, HttpServletRequest request) throws Exception {
        //根据sessionid 校验是否登录
        HttpSession session = request.getSession();
        String sessionId1 = (String) session.getAttribute(userName);
        if (StringUtils.isEmpty(sessionId1) && !sessionId1.equals(sessionId)) {
            return new ResponseMessageVo("0", "请先登录");
        }
        Map data = new HashMap();
        data.put("sessionId",sessionId);
        data.put("userName",userName);
        return new ResponseMessageVo("200",port,data);
    }
}
